//
//  MainViewController.swift
//  sinaWeiBo
//
//  Created by weixq on 15/7/30.
//  Copyright © 2015年 weixq. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        setupComposButton()
    }
    
    /// 设置compos按钮的fram
    private func setupComposButton(){
        //计算frame
        let x = UIScreen.mainScreen().bounds.width / CGFloat(viewControllers!.count)
        let rect = CGRect(x: 0, y: 0, width: x, height: tabBar.bounds.height)
        composButton.frame = CGRectOffset(rect, 2*x, 0)
    }
    
    /// 定义监听方法
    // moder 临时出来的控制器
    func composButtonClick(){
        
        let vc = UserAccount.userLogon ? ComposeViewController(): OAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
        
        
    } 
    
    /// 添加所有子控制器
    private func addChildViewControllers() {
        addChildViewController(HomeTableViewController(), title: "首页", name: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", name: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DisCoverTableViewController(), title: "发现", name: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", name: "tabbar_profile")
    }
    
    /// 定义子控制器相关属性
    private func addChildViewController(vc: UIViewController, title:String, name:String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named: name)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
        
    }
    
    /// 定义compos按钮属性
    private lazy var composButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(button)
        
        button.addTarget(self, action: "composButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()

}
